package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"tofu-manager/cache"
	"tofu-manager/models"
	"tofu-manager/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	redis_login_key := "redis_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errCount > 5 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return

}
func Role(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  notes
		  LEFT JOIN role_notes ON role_notes.note_id = notes.id
		  WHERE role_notes.note_id = 1
	*/
	var role models.Note
	models.DB.Table("notes").
		Joins("LEFT JOIN role_notes ON role_notes.note_id = notes.id").
		Where("role_notes.note_id = ?", rid).
		Debug().
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": role,
	})
	return
}
func User(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.role_id = roles.id
		  WHERE user_roles.role_id = 1
	*/
	var user models.Role
	models.DB.Table("roles").
		Joins(" LEFT JOIN user_roles ON user_roles.role_id = roles.id").
		Where("user_roles.role_id = ?", uid).
		Debug().
		Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": user,
	})
	return
}
func Add(c *gin.Context) {
	ShopName := c.PostForm("ShopName")
	shop := models.Shop{

		ShopName: ShopName,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Oder(c *gin.Context) {
	OrderName := c.PostForm("OrderName")
	Price, _ := strconv.Atoi(c.PostForm("Price"))
	Pid, _ := strconv.Atoi(c.PostForm("Pid"))
	order := models.Order{
		OrderName: OrderName,
		Price:     Price,
		Pid:       Pid,
	}
	err := models.DB.Create(&order).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []models.Product
	/*
		SELECT
			orders.id as Id,
			orders.order_name as OrderName,
			orders.price as OrderPrice,
			orders.pid as OrderPid,
			shops.shop_name as ShopName,
			shops.order_no as ShopNo
		FROM
			orders
			LEFT JOIN shops ON orders.pid = shops.id
	*/
	redis_list_key := "redis_list_" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		models.DB.Table("orders").
			Select(
				"orders.id as Id",
				"orders.order_name as OrderName",
				"orders.price as OrderPrice",
				"orders.pid as OrderPid",
				"shops.shop_name as ShopName",
				"shops.order_no as ShopNo",
			).
			Joins("LEFT JOIN shops ON orders.pid = shops.id").
			Offset(offset).Limit(size).Debug().Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	var total int64
	models.DB.Model(&models.Order{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  500,
		"msg":   "查询成功",
		"data":  list,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var detail models.Order

	redis_detail_key := "redis_detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if result == "" {
		models.DB.Where("id = ?", id).Find(&detail)
		jsonData, _ := json.Marshal(detail)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &detail)
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": detail,
	})
	return
}
